package com.ruoyi.web.controller.report;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.enums.DataType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.report.domain.WalmartReport;
import com.ruoyi.report.service.WalmartInventoryReportService;
import com.ruoyi.report.service.WalmartReportService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * walmart商品报告Controller
 *
 * @author luxiaoyu
 * @date 2025-02-10
 */
@RestController
@RequestMapping("/datacenter/report")
@Component("walmart")
public class WalmartReportController extends BaseController {
	@Autowired
	private WalmartReportService walmartReportService;


	/**
	 * 查询walmart商品报告列表
	 */
	@PreAuthorize("@ss.hasPermi('datacenter:report:list')")
	@GetMapping("/list")
	public TableDataInfo list(WalmartReport walmartReport) {
		startPage();
		List<WalmartReport> list = walmartReportService.selectWalmartReportList(walmartReport);
		return getDataTable(list);
	}

//    /**
//     * 导出walmart商品报告列表
//     */
//    @PreAuthorize("@ss.hasPermi('datacenter:report:export')")
//    @Log(title = "walmart商品报告", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, WalmartReport walmartReport)
//    {
//        List<WalmartReport> list = walmartReportService.selectWalmartReportList(walmartReport);
//        ExcelUtil<WalmartReport> util = new ExcelUtil<WalmartReport>(WalmartReport.class);
//        util.exportExcel(response, list, "walmart商品报告数据");
//    }
//

	/**
	 * 获取walmart商品报告详细信息
	 */
	@PreAuthorize("@ss.hasPermi('datacenter:report:query')")
	@GetMapping
	public TableDataInfo getInfo(WalmartReport walmartReport) {
		startPage();
		List<?> list = new ArrayList<>();
		if (Objects.equals(walmartReport.getReportType(), DataType.ITEM.getValue())) {
			// 项目报告详情请求
			list = walmartReportService.selectWalmartReportItemByItemReportId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.INVENTORY.getValue())) {
			list = walmartReportService.selectListWalmartReportInventoryByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.SHIPPING_CONFIGURATION.getValue())) {
            list = walmartReportService.selectListWalmartReportShippingConfigurationByRequestId(walmartReport.getRequestId());
        } else if (Objects.equals(walmartReport.getReportType(), DataType.SHIPPING_PROGRAM.getValue())) {
            list = walmartReportService.selectListWalmartReportShippingProgramByRequestId(walmartReport.getRequestId());
        } else if (Objects.equals(walmartReport.getReportType(), DataType.RETURN_OVERRIDES.getValue())) {
			list = walmartReportService.selectListWalmartReportReturnOverridesByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.PROMO.getValue())) {
			list = walmartReportService.selectListWalmartReportProMoByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.FITMENT_MISSING_ATTR.getValue())) {
			list = walmartReportService.selectListWalmartFitmentMissingAttrByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.FITMENT_ACES_COVERAGE.getValue())) {
			list = walmartReportService.selectListWalmartFitmentAcesCoverageByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.BUYBOX.getValue())) {
			list = walmartReportService.selectListWalmartBuyBoxByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.LAGTIME.getValue())) {
			list = walmartReportService.selectListWalmartLagTimeByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.ASSORTMENT_RECOMMENDATIONS.getValue())) {
			list = walmartReportService.selectListWalmartAssortmentRecommendationsByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.CANCELLATION.getValue())) {
			list = walmartReportService.selectListWalmartCancellationByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.CPA.getValue())) {
			list = walmartReportService.selectListWalmartCpaByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.DELIVERY_DEFECT.getValue())) {
			list = walmartReportService.selectListWalmartDeliveryDefectByRequestId(walmartReport.getRequestId());
		} else if (Objects.equals(walmartReport.getReportType(), DataType.ITEM_PERFORMANCE.getValue())) {
			list = walmartReportService.selectListWalmartItemPerformanceByRequestId(walmartReport.getRequestId());
		}

		// 返回空集合避免空指针问题
		return getDataTable(list != null ? list : Collections.emptyList());
	}

//

	/**
	 * 新增walmart商品报告
	 */
	@PreAuthorize("@ss.hasPermi('datacenter:report:add')")
	@Log(title = "walmart商品报告", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody WalmartReport WalmartReport) throws Exception {
		return toAjax(walmartReportService.insertWalmartReport(WalmartReport));
	}

	/**
	 * 刷新walmart商品报告
	 */
	public void refreshReportStatus() {
		try{
			walmartReportService.refreshReportStatus();
		}catch (Exception e){
			throw new ServiceException(e.getMessage());
		}
	}


	/**
	 * 获取walmart平台后台报告数据列表
	 */
	public void getReportRequest() {
		try{
			walmartReportService.getReportRequest();
		}catch (Exception e){
			throw new ServiceException(e.getMessage());
		}
	}



//    /**
//     * 删除walmart商品报告
//     */
//    @PreAuthorize("@ss.hasPermi('datacenter:report:remove')")
//    @Log(title = "walmart商品报告", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{itemReportIds}")
//    public AjaxResult remove(@PathVariable Long[] itemReportIds)
//    {
//        return toAjax(walmartReportService.deleteWalmartReportItemByItemReportIds(itemReportIds));
//    }

	/**
	 * 下载walmart商品报告
	 */
	@PreAuthorize("@ss.hasPermi('datacenter:report:download')")
	@PostMapping("/download")
	public ResponseEntity<Resource> downloadReport(WalmartReport walmartReport) {
		// 使用 Service 拼装文件路径
		String filePath = walmartReportService.getFilePath(walmartReport.getRequestId(), new SimpleDateFormat("yyyy-MM-dd").format(walmartReport.getRequiredDateTime()));

		File file = new File(filePath);

		if (!file.exists()) {
			return ResponseEntity.notFound().build();
		}

		// 设置响应头，指定文件名
		String filename = file.getName();
		Path path = Paths.get(file.getAbsolutePath());

		Resource resource = new FileSystemResource(path);

		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
				.contentType(MediaType.APPLICATION_OCTET_STREAM)
				.body(resource);
	}
}
